import UIKit

class ProjectDetailViewController: BaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ChangePage {
    
    func change(toPage idx: Int) {
        
        if let vc = page.viewControllers?[0] {
            
            if let currentIndex = ctls.index(of: vc) {
                
                if currentIndex < idx {
                    
                    page.setViewControllers([ctls[idx]], direction: .forward, animated: true, completion: nil)
                    
                } else {
                    page.setViewControllers([ctls[idx]], direction: .reverse, animated: true, completion: nil)
                }
                
            }
        }
    }
    
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx > 0 {
                
                return ctls[idx - 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx < ctls.count - 1 {
                
                return ctls[idx + 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed {
            
            let vc = pageViewController.viewControllers![0]
            
            if let index = ctls.index(of: vc) {
                
                slide.slide(toPosition: index)
                
            }
            
        }
    }
    
    
    var applyid = "a8c5d72ffa3b4788b0cb87a6913579ca"
    
    var applyType = ""
    
    var ctls: Array<UIViewController> = []
    
    let page = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
    
    let slide = SlidePageView.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 55)))
    
    let approvalBtn = UIButton(type: .system)
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        slide.width = self.view.width
        
        slide.configTitles(["基础信息","预算信息"])
        
        page.delegate = self
        
        page.dataSource = self
        
        slide.delegate = self
        
        slide.backgroundColor = UIColor.white
        
        self.view.addSubview(slide)
        
        page.view.backgroundColor = UIColor.white
        
        self.view.addSubview(page.view)
        
        for view in page.view.subviews {
            if let scroll = view as? UIScrollView {
                
                scroll.delegate = slide
                
            }
        }
        
        let baseinfo = PartialTableViewController()
        
        baseinfo.partialCount = 14
        
        let contents = [["项目名称":""],["项目状态":""],["项目编号":""],["项目简称":""],["业务产品类别":""],["项目类型":""],["项目级别":""],["所属部门":""],["项目经理":""],["项目预计收入(元)":""],["项目预计成本(元)":""],["预计毛利率":""],["合同签署状况":""],["立项日期":""],["客户经理":""],["客户单位":""],["客户单位项目负责人":""],["计划开始日期":""],["计划结束日期":""],["预计工作量(人月)":""],["预计投入人数":""],["项目实施地":""],["事业部协作情况":""],["项目目标":""],["项目简介":""],["预计项目进度安排":""],["项目交付验收标准":""],["备注":""]]
        
        baseinfo.source = contents
        
        ctls.append(baseinfo)
        
        let predicate = PredicateTableViewController()
        
        ctls.append(predicate)
        
        page.setViewControllers([ctls[0]], direction: .forward, animated: false, completion: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshBtn), name: NSNotification.Name("RefreshDetail"), object: nil)
        
        for view in page.view.subviews {
            if view is UIScrollView {
                let scroll = view as! UIScrollView
                scroll.bounces = false
            }
        }
        
    }
    
    @objc func refreshBtn()->Void{DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 3000)) {
            self.popobjc()
        }
    }
    
    @objc func approvalAction(_ : UIButton) -> Void {
        
        
         let approval = ApprovalSuggestionViewController()
        approval.applyId = self.applyid
        
        approval.businessType = self.applyType
        
         self.navigationController?.present(vc: approval)
        
    }
    
    override func viewWillLayoutSubviews() {
        
        super.viewWillLayoutSubviews()
        
        page.view.frame = CGRect(origin: CGPoint(x: 0, y: slide.bottom), size: CGSize(width: self.view.width, height: self.view.height - slide.height))
        
    }
    
    
    override var names: Array<String> {
        get{
            return ["detail","refresh"]
        }
    }
    
    override func success(for name: String) -> NetSuccess{
        
        func suc(json: JSON)->Void{
            
            slide.configTitles(["基本信息","审批记录"])
            
            var contents: Array<Dictionary<String,String?>> = []
            
            let data = json.contents?["data"]?.contents
            
            let changeNum = data?["changeNum"]?.rawString() ?? ""
            
            contents.append(["变更申请号":changeNum])
            
            let projectArchivesBO = data?["projectArchivesBO"]?.dictionary ?? ["":JSON()]
            
            let projectName = projectArchivesBO["gsProjName"]?.rawString() ?? ""
            
            contents.append(["项目名称":projectName])
            
            let projectNum = projectArchivesBO["projectNumber"]?.rawString() ?? ""
            
            contents.append(["项目编号":projectNum])
            
            let projectManager = projectArchivesBO["projManagerName"]?.rawString() ?? ""
            
            contents.append(["项目经理":projectManager])
            
            let projectType = projectArchivesBO["projType"]?.rawValue as? Int ?? -1
            
            switch projectType {
            case 1:
                contents.append(["项目类型":"合同开发"])
            case 2:
                contents.append(["项目类型":"自主研发"])
            case 3:
                contents.append(["项目类型":"生产销售类"])
            case 4:
                contents.append(["项目类型":"工程类"])
            case 5:
                contents.append(["项目类型":"运维服务类"])
            case 6:
                contents.append(["项目类型":"咨询类"])
            case 7:
                contents.append(["项目类型":"融资性租赁"])
            case 8:
                contents.append(["项目类型":"经营性租赁"])
            case 9:
                contents.append(["项目类型":"综合管理类"])
            case 10:
                contents.append(["项目类型":"其他类"])
            case 11:
                contents.append(["项目类型":"实施类"])
            default:
                contents.append(["项目类型":"其他"])
            }
            
            let projectLevel = projectArchivesBO["projLevel"]?.rawValue as? Int ?? 0
            
            switch projectLevel {
            case 1:
                contents.append(["项目级别":"公司"])
            default:
                contents.append(["项目级别":"部门"])
            }
            
            let requestDepartment = projectArchivesBO["projDept"]?.rawString() ?? ""
            
            contents.append(["申请部门":requestDepartment])
            
            let assistDepartment = projectArchivesBO["assistDept"]?.rawString() ?? ""
            
            contents.append(["协同部门":assistDepartment])
            
            let projEstimatedRevenue = projectArchivesBO["projEstimatedRevenue"]?.rawValue as? Int ?? 0
            
            contents.append(["项目预算收入(元)":String(projEstimatedRevenue / 100).rmbformat])
            
            let projBudget = projectArchivesBO["projBudget"]?.rawValue as? Int ?? 0
            
            contents.append(["项目预算成本(元)":String(projBudget / 100).rmbformat])
            
            let changeTitle = data?["changeTitle"]?.rawString() ?? ""
            
            contents.append(["变更标题":changeTitle])
            
            let changeType = data?["changeType"]?.rawValue as? Int ?? 0
            
            switch changeType {
            case 1:
                contents.append(["变更类型":"项目计划变更"])
            case 2:
                contents.append(["变更类型":"项目预算变更"])
            default:
                contents.append(["变更类型":"其他变更"])
            }
            
            let changeLevel = data?["changeLevel"]?.rawValue as? Int ?? 0
            
            switch changeLevel {
            case 1:
                contents.append(["变更严重级别":"严重"])
            case 2:
                contents.append(["变更严重级别":"中度"])
                
            default:
                contents.append(["变更严重级别":"中度"])
            }
            
            let modifyer = data?["changeEmp"]?.rawString() ?? ""
            
            contents.append(["变更申请人":modifyer])
            
            let modifyContent = data?["changeContent"]?.rawString() ?? ""
            
            contents.append(["变更内容描述":modifyContent])
            
            let modifyReason = data?["changeContent"]?.rawString() ?? ""
            
            contents.append(["变更原因分析":modifyReason])
            
            let modifyAffect = data?["changeAffect"]?.rawString() ?? ""
            
            contents.append(["变更影响分析":modifyAffect])
            
            let contentsViewController = TitleContentTableViewController()
            
            contentsViewController.source = contents
            
            self.ctls.append(contentsViewController)
            
            self.page.setViewControllers([self.ctls[0]], direction: .forward, animated: false) { (finished) in
                
            }
            
            //            let details = data?["details"]?.contents
            //
            //            let purchase = PurchaseTableViewController()
            //
            //            var contents: Array<Dictionary<String,String?>> = []
            //
            //            contents.append(["采购单号:":details?["serialNumber"]?.rawString()])
            //
            //            if let type = details?["type"]?.rawString() {
            //
            //                if type == "serviceEngineering" {
            //                    contents.append(["采购类型":"工程类"])
            //                } else {
            //                    contents.append(["采购类型":"人力类"])
            //                }
            //
            //            } else {
            //                contents.append(["采购类型":"未知"])
            //            }
            //
            //            contents.append(["任务名称:":details?["serialNumber"]?.rawString()])
            //
            //            contents.append(["需求日期:":details?["demandTime"]?.rawString()])
            //
            //            contents.append(["采购依据:":details?["purchaseBasisName"]?.rawString()])
            //
            //            if let amount = details?["estimatedAmount"]?.rawValue as? Int {
            //
            //                let rmb = amount / 100
            //
            //                contents.append(["预算金额(元):":String(rmb)])
            //
            //                contents.append(["估算金额(元):":String(rmb)])
            //
            //            } else {
            //
            //                contents.append(["预算金额(元):":""])
            //
            //                contents.append(["估算金额(元):":""])
            //            }
            //
            //            if let ifFrame = details?["weatherFrame"]?.rawValue as? Bool {
            //                if ifFrame == true {
            //                    contents.append(["是否框架:":"是"])
            //                } else {
            //                    contents.append(["是否框架:":"否"])
            //                }
            //            } else {
            //                contents.append(["是否框架:":"否"])
            //            }
            //
            //            contents.append(["建议采购方式:":details?["procurementMethod"]?.rawString()])
            //
            //            contents.append(["暂定包数:":details?["provisionalPacketNumber"]?.rawString()])
            //
            //            contents.append(["付款方式:":details?["paymentMethod"]?.rawString()])
            //
            //            contents.append(["进项金额(元):":details?["incomingAmount"]?.rawString()])
            //
            //            contents.append(["质保期(月):":details?["warrantyPeriod"]?.rawString()])
            //
            //            contents.append(["专用资质条件:":details?["qualificationConditions"]?.rawString()])
            //
            //            contents.append(["服务期限:":details?["servicePeriod"]?.rawString()])
            //
            //            purchase.source = contents
            //
            //            var attachs: Array<JSON> = []
            //
            //            guard let attachments = details?["attachFiles"]?.array else {
            //                return
            //            }
            //            for item in attachments {
            //                attachs.append(item)
            //            }
            //
            //            purchase.documents = attachs
            //
            //            ctls.append(purchase)
            //
            //            self.page.setViewControllers([purchase], direction: .forward, animated: false, completion: nil)
            //
            //            let type = details?["type"]?.rawString()
            //
            //            if type == "serviceEngineering" {
            //                //3ge标签
            //
            //                slide.configTitles(["采购信息","项目信息","审批记录"])
            //
            //                let projectInfo = ProjectInfoViewController.init()
            //
            //                var contents: Array<Dictionary<String,String?>> = []
            //
            //                contents.append(["关联项目:":details?["projectName"]?.rawString()])
            //
            //                contents.append(["项目编号:":details?["proSerialNumber"]?.rawString()])
            //
            //                contents.append(["项目负责人:":details?["projManagerName"]?.rawString()])
            //
            //                let applicantInfo = details?["applicantInfo"]?.contents
            //
            //                contents.append(["联系电话:":applicantInfo?["phone"]?.rawString()])
            //
            //                contents.append(["申请部门:":applicantInfo?["orgName"]?.rawString()])
            //
            //                contents.append(["项目背景:":applicantInfo?["projectBackground"]?.rawString()])
            //
            //                projectInfo.source = contents
            //
            //                ctls.append(projectInfo)
            //
            //            }
            //
            //            let approvalList = ApprovalRecordListViewController()
            //
            //            if let list = data?["approvalList"]?.array {
            //
            //                approvalList.source = list
            //
            //                approvalList.tableView.reloadData()
            //            }
            //
            //            ctls.append(approvalList)
        }
        
        func refresh(json: JSON)->Void{
            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
                return
            }
            
            if canoperate == true {
                approvalBtn.isEnabled = true
            } else {
                approvalBtn.isEnabled = false
            }
        }
        
        return name == "detail" ? suc : refresh
        
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        return ["id":self.applyid]
    }
    
    override func path(for name: String) -> String{
        return "projectManage/mobile/sys/projectchange/view"
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
}


